package com.china08.yxyapi.rabbitmq.listener.continuedu;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.config.RabbitConfig;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduStatisticsSchoolTask;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduTask;
import com.china08.yxyapi.entity.mg.continuedu.YxyContinueduUserTask;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduStatisticsSchoolTaskRepository;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduTaskRepository;
import com.china08.yxyapi.repository.mg.continuedu.YxyContinueduUserTaskRepository;

/**
 * 
 * @annotation: 继续教育统计
 * @author: yaoguanglin
 */
@Component
@EnableRabbit
public class ContinueduStatisticListener {

    private static final Logger LOGGER = Logger.getLogger(ContinueduStatisticListener.class);

    @Autowired
    private YxyContinueduStatisticsSchoolTaskRepository statisticsSchoolTaskRepository;

    @Autowired
    private YxyContinueduTaskRepository yxyContinueduTaskRepository;

    @Autowired
    private YxyContinueduUserTaskRepository yxyContinueduUserTaskRepository;

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 检查任务状态是否已截止 ---更新任务状态
     * 
     * @throws ParseException
     * 
     */
    @RabbitListener(queues = RabbitConfig.YW_CONTINUEDU_USER_TASK_TWO)
    public void userTaskUpd(Map<String, Object> map) throws ParseException {

        /**
         * 统计任务表数据
         */
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        date = sdf.parse(sdf.format(date));

        // 查询截止时间小于今天的23点并且状态不为已截止的
        List<YxyContinueduTask> tasks = yxyContinueduTaskRepository.findByEndDateLessThanAndStatusNot(date, 1);
        if (tasks != null && tasks.size() > 0) {
            for (YxyContinueduTask yxyContinueduTask : tasks) {
                yxyContinueduTask.setStatus(1);
                yxyContinueduTaskRepository.save(yxyContinueduTask);
            }
        }

        // 修改任务表已开始并且未到截止时间的任务状态为已开始
        List<YxyContinueduTask> tasks1 = yxyContinueduTaskRepository.findByBeginDateAndEndDateGreaterThanEqual(date,
                date);
        if (tasks1 != null && tasks1.size() > 0) {
            for (YxyContinueduTask yxyContinueduTask : tasks1) {
                yxyContinueduTask.setStatus(0);
                yxyContinueduTaskRepository.save(yxyContinueduTask);
            }
        }
        /**
         * 统计用户——任务表数据
         */
        // 查询任务截止时间小于现在时间 并且状态不为未完成
        List<YxyContinueduUserTask> userTasks = yxyContinueduUserTaskRepository.findByStatusNotAndEndDateLessThan(1,
                date);
        // 修改为未完成
        if (userTasks != null && userTasks.size() > 0) {
            for (YxyContinueduUserTask yxyContinueduUserTask : userTasks) {
                yxyContinueduUserTask.setStatus(-1);
                yxyContinueduUserTaskRepository.save(yxyContinueduUserTask);
            }
        }

    }

    /**
     * 根据学校ID 更新此学校完成任务的教师数量及结业率
     * 
     */
    @RabbitListener(queues = RabbitConfig.YW_CONTINUEDU_FINISH_TASK)
    public void finishTaskStatis(Map<String, Object> mapTask) {
        String schoolId = (String) mapTask.get("schoolId");
        String taskId = (String) mapTask.get("taskId");
        //
        YxyContinueduStatisticsSchoolTask schoolTask = statisticsSchoolTaskRepository.findBySchoolIdAndTaskId(schoolId,
                taskId);

        // 更新结业人数
        Long completeCount = schoolTask.getCompleteCount() + 1l;
        schoolTask.setCompleteCount(completeCount);

        Long applyCount = schoolTask.getApplyCount();
        // 更新结业率 保留两位小数
        double rate = (float) completeCount / applyCount;
        BigDecimal b = new BigDecimal(rate);
        Double completeRate = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
        schoolTask.setCompleteRate(completeRate);
        statisticsSchoolTaskRepository.save(schoolTask);

        /**
         * 更新任务表数据
         */
        YxyContinueduTask yxyContinueduTask = yxyContinueduTaskRepository.findById(taskId);
        // 更新结业人数
        Long completeCountTask = yxyContinueduTask.getCompleteCount() + 1l;
        yxyContinueduTask.setCompleteCount(completeCountTask);

        Long applyCountTask = yxyContinueduTask.getApplyCount();
        // 更新结业率 保留两位小数
        double rateTask = (float) completeCountTask / applyCountTask;
        BigDecimal bTask = new BigDecimal(rateTask);
        Double completeRateTask = bTask.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
        yxyContinueduTask.setCompleteRate(completeRateTask);

        yxyContinueduTaskRepository.save(yxyContinueduTask);

    }

    /**
     * 根据学校ID 统计此学校的报名人数
     * 
     */
    @RabbitListener(queues = RabbitConfig.YW_CONTINUEDU_ENROL_ONE)
    public void enrolStatis(Map<String, Object> mapTask) {
        String schoolId = (String) mapTask.get("schoolId");
        String taskId = (String) mapTask.get("taskId");
        Map<String, String> map = restTemplate.getForObject(yxyApiYxUrl + "/comm/school/" + schoolId, Map.class);

        String schoolNick = map.get("schoolNick");
        String areaIdProvince = map.get("areaIdProvince");
        String areaIdCity = map.get("areaIdCity");
        String areaIdDistrict = map.get("areaIdDistrict");

        YxyContinueduStatisticsSchoolTask schoolTask = statisticsSchoolTaskRepository.findBySchoolIdAndTaskId(schoolId,
                taskId);

        // 更新学校报名人数统计
        if (schoolTask == null) {
            // 该学校的教师第一次报名,初始化数据
            YxyContinueduStatisticsSchoolTask task = new YxyContinueduStatisticsSchoolTask();
            task.setApplyCount(1l);
            task.setAreaCodeCity(areaIdCity);
            task.setAreaCodeDistrict(areaIdDistrict);
            task.setAreaCodeProvince(areaIdProvince);
            task.setCompleteCount(0l);
            task.setCompleteRate(0.0);
            task.setSchoolId(schoolId);
            task.setSchoolNick(schoolNick);
            task.setTaskId(taskId);
            statisticsSchoolTaskRepository.save(task);

        } else {
            // 更新报名人数、 结业率
            Long applyCount = schoolTask.getApplyCount() + 1l;
            schoolTask.setApplyCount(applyCount);
            Long completeCount = schoolTask.getCompleteCount();
            // 重新计算结业率、保留两位小数
            double rate = (float) completeCount / applyCount;
            BigDecimal b = new BigDecimal(rate);
            Double completeRate = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;

            schoolTask.setCompleteRate(completeRate);
            statisticsSchoolTaskRepository.save(schoolTask);
        }

        /**
         * 更新任务表报名数据
         */
        YxyContinueduTask yxyContinueduTask = yxyContinueduTaskRepository.findById(taskId);
        Long applyCount = yxyContinueduTask.getApplyCount() + 1l;
        yxyContinueduTask.setApplyCount(applyCount);
        // 重新计算结业率
        Long completeCount = yxyContinueduTask.getCompleteCount();
        double rate = (float) completeCount / applyCount;
        BigDecimal b = new BigDecimal(rate);
        Double completeRate = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
        yxyContinueduTask.setCompleteRate(completeRate);
        yxyContinueduTaskRepository.save(yxyContinueduTask);

    }
}
